#!/bin/sh
# Windows Install
# By Sergey_Galan (Serhii Halaniuk)
# Copyright (c) 2024, Sergey_Galan (Serhii Halaniuk). All Right Reserved
# Credit: Wimlib, ntfs-3g-utils, Platypus, BCD-SYS



Time()
{
finishTime=$(date -u "+%s")
processedTime=$(expr $finishTime - $startTime)

if [[ $processedTime -gt 3599 ]]; then
    processedTime=$(printf "%dh%dm%ds\n" $((processedTime/3600%3600)) $((processedTime/60%60)) $((processedTime%60)))

elif [[ $processedTime -gt 59 ]]; then
    processedTime=$(printf "%dm%ds\n" $((processedTime/60%60)) $((processedTime%60)))
 else
    processedTime=$(printf "%ds\n" $((processedTime)))
fi

}

DiskPartition()
{
s=s

lan=`defaults read -g AppleLocale | cut -d "_" -f1`

if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Диск и/или раздел disk$x$s$y не существует!"\r"Введите правильные значения диск, раздел в меню программы.""
    exit
fi

if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Диск і/або розділ disk$x$s$y не існує!"\r"Введіть правильні значення диск, розділ в меню програми.""
    exit
fi

echo "Info:\r\r\r\r\r\r\r"Disk and/or partition disk$x$s$y doesn\'\t exist!"\r"Enter the correct drive and partition values ​​in the program menu.""
exit
}


DiskMap()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`

if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Некорректный раздел диска!"\r"Должна быть схема разделов GUID.""
    exit
fi

if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Некоректний розділ диска!"\r"Повинна бути схема розділів GUID.""
    exit
fi

echo "Info:\r\r\r\r\r\r\r"Incorrect disk partition!"\r"There shall be GUID Partition Map.""
exit
}


DisableDisk()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`

if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Невозможно отключить Disk"$x" !"\r"Устраните причину.""
    exit
fi

if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Неможливо вимкнути Disk"$x" !"\r"Усуньте причину.""
    exit
fi

echo "Info:\r\r\r\r\r\r\r"Can\'\t turn off Disk"$x" !"\r"Eliminate the cause.""
exit
}


DiskFormatGTP()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`

if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Некорректный раздел, или формат раздела!"\r"Формат должен быть FAT32 или exFAT.""
    exit
fi

if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Некоректне розділ, або формат розділу!"\r"Формат повинен бути FAT32 або exFAT.""
    exit
fi

echo "Info:\r\r\r\r\r\r\r"Incorrect partition, or format of disk partition!"\r"The format must be FAT32 or exFAT.""
exit
}


DiskFormatMBR()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`

if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Некорректный раздел, или формат раздела!"\r"Формат должен быть exFAT.""
    exit
fi

if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Некоректне розділ, або формат розділу!"\r"Формат повинен бути exFAT.""
    exit
fi

echo "Info:\r\r\r\r\r\r\r"Incorrect partition, or format of disk partition!"\r"The format must be exFAT.""
exit
}

IndexNumber()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`

if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Index: "$i" в этом образе не существует!"\r"Введите правильное значение Index в меню программы.""
    exit
fi

if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Index: "$i" у цьому образі не існує!"\r"Введіть правильне значення Index у меню програми.""
    exit
fi

echo "Info:\r\r\r\r\r\r\r"Index: "$i" does not exist in this image!"\r"Enter the correct Index value ​​in the program menu.""
exit
}


imgTest()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`

if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Образ не существует!"\r"Перетяните на окно программы образ с расширением iso, wim или esd.""
    exit
fi

if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Образ не існує!"\r"Перетягніть на вікно програми образ із розширенням iso, wim або esd.""
    exit
fi

echo "Info:\r\r\r\r\r\r\r"The image doesn\'\t exist!"\r"Drag an image with an iso, wim or esd extension onto the program window.""
exit
}


Password()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`

if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Неверный пароль!"\r"Введите пароль администратора.""
    exit
fi

if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Невірний пароль!"\r"Введіть пароль адміністратора.""
    exit
fi

echo "Info:\r\r\r\r\r\r\r"incorrect password!"\r"Enter admin password.""
exit
}


NoSystemPartition()
{
s=s

lan=`defaults read -g AppleLocale | cut -d "_" -f1`

if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Не удалось восстановить загрузчик!"\r"Возможно на disk$x$s$y нет системы Windows, или она повреждена.""
    sleep 1
    open /Volumes/EFI/EFI
    exit
fi

if [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Неможливо відновити завантажувач!"\r"Можливо, на disk$x$s$y немає системи Windows, або вона пошкоджена.""
    sleep 1
    open /Volumes/EFI/EFI
    exit
fi

echo "Info:\r\r\r\r\r\r\r"Failed to recover bootloader!"\r"Perhaps there is no Windows system on disk$x$s$y, or it is damaged.""
sleep 1
open /Volumes/EFI/EFI
exit
}


RepairStart()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`

if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r\r"Восстанавливаем EFI загрузчик Windows.""

elif [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r\r"Відновлюємо EFI завантажувач Windows.""

else
    echo "Info:\r\r\r\r\r\r\r\r"Restoring the EFI Windows bootloader.""
fi
}


InstallStart()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`

ext="${Image##*.}"
if [[ `echo "wim esd" 2>&1 | grep -i $ext` ]]; then
    IndexInf="$(./tools/bin/wimlib-imagex info "$Image" | sed -e s/'Display Name:'//g | sed -e s/'Product Name:'//g | grep 'Index:\|Name:\|Flags:\|System Root:' | grep -v 'Boot' | tr -s ' ' ' ' | sed -e s/'Name:'//g | sed -e s/'System Root:'//g | sed -e s/'Flags:'//g | tr -d "\n")"
    IndexInf=${IndexInf/*'Index: '$i ''/}
    IndexInf=${IndexInf/'Index:'*/}
elif [[ `echo "iso" 2>&1 | grep -i $ext` ]]; then
    IndexInf="$(./tools/bin/wimlib-imagex info /V*/*/sources/install.* | grep 'Index:\|Display Name:' | grep -v 'Boot' | tr -s ' ' ' ' | sed -e s/'Display Name'/'Edition'/g  | tr -d "\n")"
    IndexInf=${IndexInf/*'Index: '$i'Edition: '/}
    IndexInf=${IndexInf/'Index:'*/}
fi

if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r"Устанавливаем"\r"$IndexInf"\r"Продолжительность установки зависит от вашего SSD/HDD накопителя."\r"$remainderTime""

elif [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r"Встановлюємо"\r"$IndexInf"\r"Тривалість установки залежить від вашого SSD/HDD накопичувача."\r"$remainderTime""

else
    echo "Info:\r\r\r\r\r\r"Installing"\r"$IndexInf"\r"The installation duration depends on your SSD/HDD drive."\r"$remainderTime""
fi
}


BackupStart()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`

if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Создаём Backup $StartData"\r"$remainderTime""

elif [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Створюємо Backup $StartData"\r"$remainderTime""

else
    echo "Info:\r\r\r\r\r\r\r"Creating Backup $StartData"\r"$remainderTime""
fi
}


Finish()
{
lan=`defaults read -g AppleLocale | cut -d "_" -f1`

if [[ "$lan" = "ru" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Процесс завершён."\r"Времени потрачено: $processedTime""

elif [[ "$lan" = "uk" ]]; then
    echo "Info:\r\r\r\r\r\r\r"Процес завершено."\r"Часу витрачено: $processedTime""

else
    echo "Info:\r\r\r\r\r\r\r"The process is completed."\r"Time is spent: $processedTime""
fi
}


TestDisk()
{
if [[ `diskutil list | grep "disk" | grep -o -e disk"$x"s"$y"` ]]; then
    :
else
    DiskPartition
fi

if [[ "$fwmode" == "uefi" ]]; then
    if [[ `diskutil list | grep "GUID_partition_scheme" | grep -o -e disk"$x"` ]]; then
        :
    else
        DiskMap
    fi
fi
if [[ `diskutil list | grep "Microsoft Basic Data" | grep -o -e disk"$x"s"$y"` || `diskutil list | grep "Windows_NTFS" | grep -o -e disk"$x"s"$y"` ]]; then
    :
else
    scheme=$(diskutil info /dev/disk"$x" | grep "Content (IOContent):" | awk '{print $3}')
    if [[ "$scheme" == "GUID_partition_scheme" ]]; then
    DiskFormatGTP
    else
    DiskFormatMBR
    fi
fi
}


TestIndex()
{

ext="${Image##*.}"
if [[ `echo "wim esd" 2>&1 | grep -i $ext` ]]; then
    pathImage="$Image"
elif [[ `echo "iso" 2>&1 | grep -i $ext` ]]; then
    pathImage=(/V*/*/sources/install.*)
fi

if [[ `./tools/bin/wimlib-imagex info "$pathImage" | tr -s ' ' ' ' | grep 'Index: '$i''` ]]; then
    :
else
    IndexNumber
fi
}


SetupComplete()
{
printf "reg add "HKLM\\SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation" /v RealTimeIsUniversal /t REG_DWORD /d 1\n"
printf "cd C:\\\\\n"
printf "attrib +r +s +h bootmgr\n"
printf "attrib +r +s +h BOOTNXT\n"
printf "attrib +r +s +h Boot /d \n"
printf "del /s /q "C:\Windows/Setup/Scripts/SetupComplete.cmd"\n"
}


build_BCD()
{
echo "Build the main BCD store..."
echo "$tf3" | sudo -S ./scripts/winload "$1" "$2" "$3" > "$HOME"/winload.txt
cp -v ./Templates/BCD-Windows "$HOME"/BCD-Windows
./tools/bin/hivexsh -d -w -f "$HOME"/winload.txt "$HOME"/BCD-Windows
if [[ "$2" == "uefi" ]]; then
    echo "Build the recovery BCD store..."
    sudo -S ./scripts/recovery "$3" > "$HOME"/recovery.txt
    cp ./Templates/BCD-Recovery "$HOME"/BCD-Recovery
    ./tools/bin/hivexsh -d -w -f "$HOME"/recovery.txt "$HOME"/BCD-Recovery
    echo "Copy the BCD hives to the ESP folders..."
    cp -v "$HOME"/BCD-Windows /Volumes/EFI/EFI/Microsoft/Boot/BCD
    cp -v "$HOME"/BCD-Recovery /Volumes/EFI/EFI/Microsoft/Recovery/BCD
elif [[ "$2" == "bios" ]]; then
      echo "Copy the main BCD hive to the boot folder..."
      cp -v "$HOME"/BCD-Windows "$HOME"/Boot/BCD
fi
rm "$HOME"/BCD-Windows
rm "$HOME"/winload.txt
if [[ "$2" == "uefi" ]]; then
    rm "$HOME"/recovery.txt
    rm "$HOME"/BCD-Recovery
fi
}


Repair()
{
echo "Media:Creates a bootloader"
RepairStart
echo "Progress:""30""% "

for efi in /Volumes/EFI*; do
  if [[ -e "$efi" ]]; then
      echo=`diskutil unmount "$efi"`
  fi
done
echo "Progress:""35""% "
if [[ ! -z $(echo "$tf3" | sudo -S fdisk /dev/disk"$x" | grep -E '2:|3:|4:' | grep -v unused) ]]; then
    printf "p\nedit 2\n0\nedit 3\n0\nedit 4\n0\nq\ny\n" | sudo -S fdisk -e /dev/disk"$x"
fi
echo "$tf3" | sudo -S diskutil mount disk"$x"s1

if [[ -f "$MountPoint"/Windows/Boot/EFI/bootmgfw.efi ]]; then
    rm -rf /Volumes/EFI/EFI/Microsoft/BOOT
    cp -rv "$MountPoint"/Windows/Boot/EFI /Volumes/EFI/EFI/Microsoft/BOOT
    echo "Progress:""50""% "
    cp -rv "$MountPoint"/Windows/Boot/Fonts /Volumes/EFI/EFI/Microsoft/BOOT
    echo "Progress:""60""% "
    if [[ -d "$MountPoint"/Windows/Boot/Resources ]]; then
        cp -rv "$MountPoint"/Windows/Boot/Resources /Volumes/EFI/EFI/Microsoft/Boot
    fi
else
    NoSystemPartition
fi

mkdir -pv /Volumes/EFI/EFI/Microsoft/Recovery/
rm -v /Volumes/EFI/EFI/Microsoft/BOOT/BCD
rm -v /Volumes/EFI/EFI/Microsoft/BOOT/bootmgfw.efi
cp -v ./bootmgfw.efi /Volumes/EFI/EFI/Microsoft/BOOT/
echo "Progress:""70""% "
langCod="$(printf "cd ControlSet001\Control\Nls\Language\nlsval InstallLanguage\nunload\n" | ./tools/bin/hivexsh "$MountPoint/Windows/System32/config/SYSTEM")"
locale="$(printf "cd Microsoft\Input\Locales\loc_"$langCod"\nlsval Fluency Model Directory\nunload\n" | ./tools/bin/hivexsh "$MountPoint/Windows/System32/config/SOFTWARE")"
build_BCD "$MountPoint" "$fwmode" "$locale"
echo "Progress:""95""% "

if [[ -e /Volumes/EFI/EFI/Clover ]] || [[ -e /Volumes/EFI/EFI/OC ]]; then
    echo "Don't install BOOT/bootx64.efi"
elif [[ "$bootx64Off" == 1 ]]; then
    echo "Deactivate Windows ESP"
    rm -rf /Volumes/EFI/EFI/BOOT 2>/dev/null
    mkdir -pv /Volumes/EFI/EFI/BOOT/
    cp -v /Volumes/EFI/EFI/Microsoft/BOOT/bootmgfw.efi /Volumes/EFI/EFI/BOOT/bootx64.efioff
else
    rm -rf /Volumes/EFI/EFI/BOOT 2>/dev/null
    mkdir -p /Volumes/EFI/EFI/BOOT/
    cp -Rv /Volumes/EFI/EFI/Microsoft/BOOT/bootmgfw.efi /Volumes/EFI/EFI/BOOT/bootx64.efi
fi
}


Install()
{

ext="${Image##*.}"
if [[ `echo "iso" 2>&1 | grep -i $ext` ]]; then
    for disk in /Volumes/*/sources/install.*; do
      if [[ -f "$disk" ]]; then
          disk="${disk///sources*}"
          diskutil eject "$disk"
      fi
    done
    hdiutil mount "$Image"
fi

echo "Media:Checking the Index"
TestIndex

InstallStart

if [[ "$fwmode" == "uefi" ]]; then
    for efi in /Volumes/EFI*; do
      if [[ -e "$efi" ]]; then
          echo=`diskutil unmount "$efi"`
      fi
    done
    if [[ ! -z $(echo "$tf3" | sudo -S fdisk /dev/disk"$x" | grep -E '2:|3:|4:' | grep -v unused) ]]; then
        printf "p\nedit 2\n0\nedit 3\n0\nedit 4\n0\nq\ny\n" | sudo -S fdisk -e /dev/disk"$x"
    fi
fi

scheme=$(diskutil info /dev/disk"$x" | grep "Content (IOContent):" | awk '{print $3}')
echo "scheme - $scheme"
pstart=$(diskutil info /dev/disk"$x"s"$y" | grep "Partition Offset:" | awk '{print $5}' | sed 's/(//')
echo "pstart - $pstart"
echo "$tf3" | sudo -S fdisk -y /dev/disk"$x"
if [[ "$fwmode" == "bios" ]]; then
    diskutil unmountDisk /dev/disk"$x" || DisableDisk
    if [[ "$scheme" == "GUID_partition_scheme" ]]; then
        #printf "r\np\nh\n$y\ny\n\ny\nn\no\nw\ny\n" | sudo ./Tools/bin/gdisk /dev/disk"$x"
        sudo -S ./Tools/bin/sgdisk -h $y /dev/disk"$x"
    fi
    pmbr=$(echo "$tf3" | sudo -S fdisk /dev/disk"$x" | grep -w $pstart | awk '{print $1}' | sed 's/*//' | sed 's/://')
    echo "\npmbr - $pmbr"
    printf "f $pmbr\nq\ny\n" | sudo -S fdisk -e /dev/disk"$x"
    sudo -S fdisk -y /dev/disk"$x"
fi

diskutil unmount disk"$x"s"$y"
echo "Media:Creating NTFS volume structures"
sleep 2
sudo -S ./Tools/bin/mkntfs -p "$pstart" -S 63 -H 255 -f -L "$PartName" /dev/disk"$x"s"$y"

ext="${Image##*.}"
if [[ `echo "wim esd" 2>&1 | grep -i $ext` ]]; then
    pathImage="$Image"
elif [[ `echo "iso" 2>&1 | grep -i $ext` ]]; then
    pathImage=(/V*/*/sources/install.*)
fi
sleep 2
sudo -S ./Tools/bin/wimlib-imagex apply "$pathImage" "$i" /dev/disk"$x"s"$y" 2>&1 |
while IFS= read -d $'\r' -r p; do
  echo "Windows Install disk"$x"s"$y" "$p""
  inst=${p/(*/}
  echo "Media:"$inst""

  if [[ `echo "$p" | grep -w "Creating"` ]]; then
      pr=${p/*(/}
      pr=${pr/"%"*}
  elif [[ `echo "$p" | grep -w "Extracting"` ]]; then
      pr=${p/*(/}
      pr=${pr/"%"*}
      pr=$(($pr+100))
  fi

  if [[ "$pr" -gt "0" ]]; then
      prr=$(($pr/2))
  else
      prr=0
  fi 2>/dev/null
  echo "Progress:""$prr""% "
  InstallStart
  tempTime=$(date -u "+%s")
  if [[ "$prOld" -lt "$pr" ]] && [[ "$tempTimeOld" -lt "$tempTime" ]]; then
      prRem=$(expr 200 - $pr)
      processedTime=$(expr "$tempTime" - "$tempTimeOld")
      remTime=$(expr $prRem \* $processedTime)

      if [[ $remTimeOld -gt "0" ]]; then
          remTime=$(expr $remTime + $remTimeOld)
          remTime=$(expr $remTime / 2)
      fi
      remTimeOld=$remTime

      if [[ $remTime -gt 3599 ]]; then
          remainderTime=$(printf "%dh%dm\n" $((remTime/3600%3600)) $((remTime/60%60)))

      elif [[ $remTime -gt 59 ]]; then
          remainderTime=$(printf "%dm%ds\n" $((remTime/60%60)) $((remTime%60)))

      elif [[ $remTime -gt "0" ]]; then
          remainderTime=$(printf "%ds\n" $((remTime)))
      fi
      tempTimeOld="$tempTime"
  fi 2>/dev/null
  prOld="$pr"
done

echo "Media:Creates a bootloader"
diskutil mount disk"$x"s"$y"
if [[ "$fwmode" == "uefi" ]]; then
    echo "$tf3" | sudo -S diskutil mount disk"$x"s1
    rm -rf /Volumes/EFI/EFI/Microsoft/BOOT
    mkdir -pv /Volumes/EFI/EFI/Microsoft/Recovery/
    cp -rv "$MountPoint"/Windows/Boot/EFI /Volumes/EFI/EFI/Microsoft/BOOT
    cp -rv "$MountPoint"/Windows/Boot/Fonts /Volumes/EFI/EFI/Microsoft/BOOT
    if [[ -d "$MountPoint"/Windows/Boot/Resources ]]; then
        cp -rv "$MountPoint"/Windows/Boot/Resources /Volumes/EFI/EFI/Microsoft/Boot
    fi
    
    langCod="$(printf "cd ControlSet001\Control\Nls\Language\nlsval InstallLanguage\nunload\n" | ./tools/bin/hivexsh "$MountPoint/Windows/System32/config/SYSTEM")"
    locale="$(printf "cd Microsoft\Input\Locales\loc_"$langCod"\nlsval Fluency Model Directory\nunload\n" | ./tools/bin/hivexsh "$MountPoint/Windows/System32/config/SOFTWARE")"
    build_BCD "$MountPoint" "$fwmode" "$locale"
    
    if [[ -e /Volumes/EFI/EFI/Clover ]] || [[ -e /Volumes/EFI/EFI/OC ]]; then
        echo "Don't install BOOT/bootx64.efi"
    elif [[ "$bootx64Off" == 1 ]]; then
        echo "Deactivate Windows ESP"
        rm -rf /Volumes/EFI/EFI/BOOT 2>/dev/null
        mkdir -pv /Volumes/EFI/EFI/BOOT/
        cp -v /Volumes/EFI/EFI/Microsoft/BOOT/bootmgfw.efi /Volumes/EFI/EFI/BOOT/bootx64.efioff
    else
        rm -rf /Volumes/EFI/EFI/BOOT 2>/dev/null
        mkdir -pv /Volumes/EFI/EFI/BOOT/
        cp -v /Volumes/EFI/EFI/Microsoft/BOOT/bootmgfw.efi /Volumes/EFI/EFI/BOOT/bootx64.efi
    fi
    KernOSRelease=`sysctl -n kern.osrelease | cut -d "." -f1`
    if [[ ${KernOSRelease} < "22" ]]; then
        mkdir ~/ntfs-volume
        echo "$tf3" | sudo -S umount /dev/disk"$x"s"$y"
        sudo -S mount -t ntfs -o rw,auto,nobrowse /dev/disk"$x"s"$y" ~/ntfs-volume
        mkdir -p ~/ntfs-volume/Windows/Setup/Scripts
        echo "reg add "HKLM\\SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation" /v RealTimeIsUniversal /t REG_DWORD /d 1" >> ~/ntfs-volume/Windows/Setup/Scripts/SetupComplete.cmd
        sudo -S umount /dev/disk"$x"s"$y"
        rm -r ~/ntfs-volume
    fi
fi

if [[ "$fwmode" == "bios" ]]; then
    echo "Copy the BIOS boot files to the system partition..."
    diskutil mount disk"$x"s"$y"
    cp -rv "$MountPoint"/Windows/Boot/PCAT "$HOME"/Boot
    cp -rv "$MountPoint"/Windows/Boot/Fonts "$HOME"/Boot
    if [[ -d "$MountPoint"/Windows/Boot/Resources ]]; then
        cp -rv "$MountPoint"/Windows/Boot/Resources "$HOME"/Boot
    fi
    mv "$HOME"/Boot/bootmgr "$HOME"
    if [[ -f "$MountPoint"/Windows/Boot/PCAT/bootnxt ]]; then
        mv "$HOME"/Boot/bootnxt "$HOME"/BOOTNXT
    fi
    
    langCod="$(printf "cd ControlSet001\Control\Nls\Language\nlsval InstallLanguage\nunload\n" | ./tools/bin/hivexsh "$MountPoint/Windows/System32/config/SYSTEM")"
    locale="$(printf "cd Microsoft\Input\Locales\loc_"$langCod"\nlsval Fluency Model Directory\nunload\n" | ./tools/bin/hivexsh "$MountPoint/Windows/System32/config/SOFTWARE")"
    build_BCD "$MountPoint" "$fwmode" "$locale"
    
    KernOSRelease=`sysctl -n kern.osrelease | cut -d "." -f1`
    if [[ ${KernOSRelease} < "22" ]]; then
        mkdir "$HOME"/ntfs-volume
        if [[ ! -f "$MountPoint/bootmgr" || ! -d "$MountPoint/Boot" ]]; then
            echo "$tf3" | sudo -S umount /dev/disk"$x"s"$y"
            sudo -S mount -t ntfs -o rw,auto,nobrowse /dev/disk"$x"s"$y" "$HOME"/ntfs-volume
            cp -rv "$HOME"/Boot "$HOME"/ntfs-volume
            cp -v "$HOME"/bootmgr "$HOME"/ntfs-volume
            if [[ -f "$HOME"/BOOTNXT ]]; then
                cp -v "$HOME"/BOOTNXT "$HOME"/ntfs-volume
            fi
            mkdir -pv "$HOME"/ntfs-volume/Windows/Setup/Scripts
            SetupComplete >> "$HOME"/ntfs-volume/Windows/Setup/Scripts/SetupComplete.cmd
        else
            echo "$tf3" | sudo -S umount /dev/disk"$x"s"$y"
            sudo -S mount -t ntfs -o rw,auto,nobrowse /dev/disk"$x"s"$y" "$HOME"/ntfs-volume
            cp -fv "$HOME"/Boot/BCD "$HOME"/ntfs-volume/Boot/
        fi
        echo "$tf3" | sudo -S umount /dev/disk"$x"s"$y"
        rm -r "$HOME"/ntfs-volume
        rm -r "$HOME"/Boot
        rm -r "$HOME"/bootmgr
        if [[ -f "$HOME"/BOOTNXT ]]; then
            rm -r "$HOME"/BOOTNXT
        fi
    else
        mkdir -pv "$HOME/Desktop/Legacy boot for Windows (disk"$x"s"$y")"
        cp -rv "$HOME"/Boot "$HOME/Desktop/Legacy boot for Windows (disk"$x"s"$y")"
        cp -v "$HOME"/bootmgr "$HOME/Desktop/Legacy boot for Windows (disk"$x"s"$y")"
        if [[ -f "$HOME"/BOOTNXT ]]; then
            cp -v "$HOME"/BOOTNXT "$HOME/Desktop/Legacy boot for Windows (disk"$x"s"$y")"
            rm -r "$HOME"/BOOTNXT
        fi
        rm -r "$HOME"/Boot
        rm -r "$HOME"/bootmgr
    fi
    diskutil unmountDisk /dev/disk"$x"
    sleep 1
    echo "$tf3" | sudo -S ./tools/bin/ms-sys -7 /dev/disk"$x"
    diskutil unmount disk"$x"s"$y"
    sudo -S ./tools/bin/ms-sys -n -p /dev/disk"$x"s"$y"
    sleep 1
fi
    echo "Media:Creates a bootloader ... Complete"
diskutil mount disk"$x"s"$y"
}


Backup()
{

diskutil unmount disk"$x"s"$y"
if [[ "$(./tools/bin/wimlib-imagex info "$DestinationFolder/WindowsBackup.wim")" ]]; then
    meaning=append
else
    meaning=capture
fi 2>/dev/null

StartData="$(date +"%Y-%m-%d-%H:%M")"

echo "$tf3" | sudo -S ./Tools/bin/wimlib-imagex "$meaning" --compress=fast --check --norpfix --config=./Exclusion_List.ini /dev/disk"$x"s"$y" "$DestinationFolder/WindowsBackup.wim" "Backup $(date +"%Y-%m-%d-%H:%M")" 2>&1 |
while IFS= read -d $'\r' -r p; do
  echo "Windows Backup disk"$x"s"$y" "$p""

  if [[ `echo "$p" | grep -w "scanned"` ]]; then
      inst=${p}
      pr=0
  elif [[ `echo "$p" | grep -w "integrity"` ]]; then
      inst=${p/(*/}
      inst=$(echo $inst | sed -e s/' integrity table'//g)
      inst=$(echo $inst | sed -e s!" of ""\"$DestinationFolder/WindowsBackup.wim"\"!!g)
      #pr=0
  else
      inst=${p/(*/}
      pr=${p/*(/}
      pr=${pr/"%"*}
  fi

  echo "Media:"$inst""
  BackupStart

  if [[ "$pr" -gt "0" ]]; then
      echo "Progress:""$pr""% "
  else
      echo "Progress:""0""% "
  fi 2>/dev/null

  tempTime=$(date -u "+%s")
  if [[ "$prOld" -lt "$pr" ]] && [[ "$tempTimeOld" -lt "$tempTime" ]]; then
      prRem=$(expr 100 - $pr)
      processedTime=$(expr $tempTime - $tempTimeOld)
      remTime=$(expr $prRem \* $processedTime)

      if [[ $remTimeOld -gt "0" ]]; then
          remTime=$(expr $remTime + $remTimeOld)
          remTime=$(expr $remTime / 2)
      fi
      remTimeOld=$remTime

      if [[ $remTime -gt 3599 ]]; then
          remainderTime=$(printf "%dh%dm\n" $((remTime/3600%3600)) $((remTime/60%60)))

      elif [[ $remTime -gt 59 ]]; then
          remainderTime=$(printf "%dm%ds\n" $((remTime/60%60)) $((remTime%60)))

      elif [[ $remTime -gt "0" ]]; then
          remainderTime=$(printf "%ds\n" $((remTime)))
      fi
      tempTimeOld="$tempTime"
  fi &> /dev/null
  prOld="$pr"
done

diskutil mount disk"$x"s"$y"
}

##################################################################################
###### Start script execution routine ############################################
##################################################################################

WindowsInstallPlist="$HOME/Library/Preferences/org.SerhiiHalan.SettingsWindowsInstall.plist" &> /dev/null
DestinationFolder="$(/usr/libexec/PlistBuddy -c "Print :DestinationFolder" "$WindowsInstallPlist")"
Image="$(/usr/libexec/PlistBuddy -c "Print :ImageWIM" "$WindowsInstallPlist")"
Mode="$(defaults read $WindowsInstallPlist PMode)"
bootx64Off="$(defaults read $WindowsInstallPlist bootx64)"
i="$(defaults read $WindowsInstallPlist DIndex)"
x="$(defaults read $WindowsInstallPlist DNumber)"
y="$(defaults read $WindowsInstallPlist DPartition)"

echo "TextPosition:Center"
echo "Media: "
diskutil mount disk"$x"s"$y"
MountPoint=`diskutil info disk"$x"s"$y" | sed -n 's/.*Mount Point: *//p'`
if [[ -d "$MountPoint" ]]; then
    PartName="${MountPoint##*/}"
else
    MountPoint=/Volumes/Windows
    PartName=Windows
fi

if [[ $Mode ==  "Restore EFI bootloader" ]]; then
    echo "################### START Repair ####################"
    fwmode="uefi"
    csrutil status
    sw_vers
    echo "Model ID:      "`sysctl -n hw.model`
    echo "Progress:""0""% "
    diskutil list
    startTime=$(date -u "+%s")
    echo "Progress:""5""% "
    echo "Info: "
    echo "Media:Password verification"
    sleep 0.5
    tf3=$(security find-generic-password -a ${USER} -s passWinInstal -w)
    echo "$tf3" | sudo -S echo "Ok" || Password
    echo "Progress:""20""% "
    TestDisk
    Repair
    echo "Progress:""100""% "
    Time
    Finish
    afplay sound/WindowsUnlock.wav &> /dev/null

    echo "Media:Creates a bootloader ... Complete"
    echo "... Complete"
    echo "... Time is spent: $processedTime"
    echo "... Current time: $(date "+%Y-%m-%d %H:%M:%S %z")"
    echo "######################## End ########################"

    echo "NOTIFICATION:Complete: disk"$x"s"$y"\rTime is spent: $processedTime\rTime: $(date "+%Y-%m-%d %H:%M:%S %z")"
    open /Volumes/EFI/EFI
    exit



elif [[ $Mode == "Windows Backup" ]]; then
    echo "################## START Backup ###################"
    mkdir "$DestinationFolder" &> /dev/null
    csrutil status
    sw_vers
    echo "Model ID:      "`sysctl -n hw.model`
    echo "Progress:""0""% "
    diskutil list
    startTime=$(date -u "+%s")
    echo "Info: "
    echo "Media:Password verification"
    sleep 0.5
    tf3=$(security find-generic-password -a ${USER} -s passWinInstal -w)
    echo "$tf3" | sudo -S echo "Ok" || Password
    echo "Media:Checking the disk and partition"
    TestDisk
    Backup
    echo "Progress:""100""% "
    Time
    Finish
    afplay sound/WindowsUnlock.wav &> /dev/null

    #echo "Media:... Complete"
    echo "... Complete"
    echo "... Time is spent: $processedTime"
    echo "... Current time: $(date "+%Y-%m-%d %H:%M:%S %z")"
    echo "######################## End ########################"

    echo "NOTIFICATION:Complete: disk"$x"s"$y"\rTime is spent: $processedTime\rTime: $(date "+%Y-%m-%d %H:%M:%S %z")"
    exit



elif [[ -f "$Image" ]] && [[ $Mode == "Install Windows UEFI" ]]; then
    echo "################## START Install ###################"
    fwmode="uefi"
    csrutil status
    sw_vers
    echo "Model ID:      "`sysctl -n hw.model`
    echo "Progress:""0""% "
    diskutil list
    startTime=$(date -u "+%s")
    echo "Info: "
    echo "Media:Password verification"
    sleep 0.5
    tf3=$(security find-generic-password -a ${USER} -s passWinInstal -w)
    echo "$tf3" | sudo -S echo "Ok" || Password
    echo "Media:Checking the disk and partition"
    TestDisk
    Install
    echo "Progress:""100""% "
    Time
    Finish
    afplay sound/WindowsUnlock.wav &> /dev/null

    echo "... Complete"
    echo "... Time is spent: $processedTime"
    echo "... Current time: $(date "+%Y-%m-%d %H:%M:%S %z")"
    echo "######################## End ########################"

    echo "NOTIFICATION:Complete: disk"$x"s"$y"\rTime is spent: $processedTime\rTime: $(date "+%Y-%m-%d %H:%M:%S %z")"
    for disk in /Volumes/*/sources/install.*; do
      if [[ -f "$disk" ]]; then
          disk="${disk///sources*}"
          diskutil eject "$disk"
      fi
    done
    open /Volumes/EFI/EFI
    open "$MountPoint"
    exit



elif [[ -f "$Image" ]] && [[ $Mode == "Install Windows legacy boot" ]]; then
    echo "################## START Install ###################"
    fwmode="bios"
    csrutil status
    sw_vers
    echo "Model ID:      "`sysctl -n hw.model`
    echo "Progress:""0""% "
    diskutil list
    startTime=$(date -u "+%s")
    echo "Info: "
    echo "Media:Password verification"
    sleep 0.5
    tf3=$(security find-generic-password -a ${USER} -s passWinInstal -w)
    echo "$tf3" | sudo -S echo "Ok" || Password
    echo "Media:Checking the disk and partition"
    TestDisk
    Install
    echo "Progress:""100""% "
    Time
    Finish
    afplay sound/WindowsUnlock.wav &> /dev/null

    echo "... Complete"
    echo "... Time is spent: $processedTime"
    echo "... Current time: $(date "+%Y-%m-%d %H:%M:%S %z")"
    echo "######################## End ########################"

    echo "NOTIFICATION:Complete: disk"$x"s"$y"\rTime is spent: $processedTime\rTime: $(date "+%Y-%m-%d %H:%M:%S %z")"
    for disk in /Volumes/*/sources/install.*; do
      if [[ -f "$disk" ]]; then
          disk="${disk///sources*}"
          diskutil eject "$disk"
      fi
    done
    open "$MountPoint"
    exit
else
    imgTest
fi
exit
